/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package frame;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import kbcquiz.App;
import library.DB;
import library.Debug;
import library.Utils;


    public class AdminNewQA extends javax.swing.JFrame {

    private TreeMap<Integer, String> categoryMap = new TreeMap<Integer, String>();
    private TreeMap<String, Integer> categoryMapID = new TreeMap<String, Integer>();
    private int QuestionID = 0;
    //private Object category;

    public AdminNewQA() {
    /** Creates new form AdminNewQA */
        initComponents();
        this.LoadCategoryData();
        setTitle("Question & Answer");
    }

    private void LoadCategoryData() {
        category.removeAllItems();
        categoryMap.clear();
        categoryMapID.clear();

        ResultSet rs = DB.execQuery("SELECT * FROM Categories");
        try {
            while (rs.next()) {
                String name = rs.getString("CatName");
                category.addItem(name);
                categoryMap.put(rs.getInt("CatID"), name);
                categoryMapID.put(name, rs.getInt("CatID"));
            }
            rs.close();
        }
        catch (SQLException ex) {
            Logger.getLogger(AdminNewQA.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        buttonGroup2 = new javax.swing.ButtonGroup();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        category = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        tfQuestion = new javax.swing.JTextArea();
        jLabel3 = new javax.swing.JLabel();
        jRadioButton1 = new javax.swing.JRadioButton();
        answer1 = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jRadioButton2 = new javax.swing.JRadioButton();
        jRadioButton3 = new javax.swing.JRadioButton();
        jRadioButton4 = new javax.swing.JRadioButton();
        answer2 = new javax.swing.JTextField();
        answer4 = new javax.swing.JTextField();
        answer3 = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        btnSave = new javax.swing.JButton();
        btnReset = new javax.swing.JButton();
        btnCancel = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("Category :");

        jLabel2.setText("Question :");

        category.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        tfQuestion.setColumns(20);
        tfQuestion.setRows(5);
        jScrollPane1.setViewportView(tfQuestion);

        jLabel3.setText("Answer 1 :");

        buttonGroup1.add(jRadioButton1);

        jLabel4.setText("Answer 2 :");

        jLabel5.setText("Answer 3 :");

        jLabel6.setText("Answer 4 :");

        buttonGroup1.add(jRadioButton2);

        buttonGroup1.add(jRadioButton3);

        buttonGroup1.add(jRadioButton4);

        jLabel7.setText("*Please check one checkbox to set the right answer");

        btnSave.setText("Save");
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });

        btnReset.setText("Reset");
        btnReset.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnResetActionPerformed(evt);
            }
        });

        btnCancel.setText("Cancel");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jScrollPane1)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jRadioButton3)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(answer3))
                                    .addComponent(jLabel3)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jRadioButton1)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(answer1, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addComponent(jLabel5))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 6, Short.MAX_VALUE)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jRadioButton4)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(answer4))
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addComponent(jLabel6)
                                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                            .addComponent(jLabel4)
                                            .addGap(117, 117, 117))
                                        .addGroup(layout.createSequentialGroup()
                                            .addComponent(jRadioButton2)
                                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                            .addComponent(answer2, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE)))))))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(jLabel1))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(33, 33, 33)
                                .addComponent(category, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(jLabel2))
                            .addGroup(layout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(jLabel7)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addComponent(btnSave, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(40, 40, 40)
                .addComponent(btnReset, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btnCancel)
                .addGap(36, 36, 36))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(category, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jRadioButton2, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(answer2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jRadioButton1)
                        .addComponent(answer1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel6)
                    .addComponent(jLabel5, javax.swing.GroupLayout.Alignment.TRAILING))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jRadioButton4)
                    .addComponent(answer4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jRadioButton3)
                        .addComponent(answer3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel7)
                .addGap(27, 27, 27)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnSave)
                    .addComponent(btnReset)
                    .addComponent(btnCancel))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnCancelActionPerformed

    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
        QuestionModel data = doValidate();
        if (this.QAEditMode) {
            data.setQuestionID(questionData.getQuestionID());
            data.setAnswersID(questionData.getAnswersID());
        }
        if (data == null) {
            return;
        }
        if (data.save() == 5) {
            Utils.Alert("Saved into database successfully");
            App.getAdminFrame().reloadData();
            App.switchDisplay(App.getAdminFrame());
        }
        else {
            Utils.Alert("There was a problem when saving data into database, please try again");
        }
    }//GEN-LAST:event_btnSaveActionPerformed

    private void btnResetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnResetActionPerformed
         if (this.QAEditMode) {
            loadData(questionData);
        }
        else {
            this.resetData();
        }
    }//GEN-LAST:event_btnResetActionPerformed
    
    private void formWindowClosing(java.awt.event.WindowEvent evt) {                                   
        this.dispose();
    }
    
    private QuestionModel doValidate() {
        QuestionModel data = null;
        // Cat
        
        if (category.getSelectedItem() == null || category.getSelectedItem().equals("")) {
            Utils.Alert("You must select question category first");
            category.requestFocus();
            return null;
        }
        if (categoryMapID.get(category.getSelectedItem().toString()) == null || categoryMapID.get(category.getSelectedItem().toString()) <= 0) {
            Utils.Alert("Category is invalidate");
            category.requestFocus();
            return null;
        }
        int catID = categoryMapID.get(category.getSelectedItem().toString());
        // Question
        if (tfQuestion.getText().trim().equals("")) {
            Utils.Alert("You must enter the question content");
            tfQuestion.requestFocus();
            return null;
        }
        String Question = tfQuestion.getText().trim();
        String[] Answers = new String[4];

        // Answer 1
        if (answer1.getText().trim().equals("")) {
            Utils.Alert("Answer 1 should not be empty");
            answer1.requestFocus();
            return null;
        }
        Answers[0] = answer1.getText().trim();

        // Answer 2
        if (answer2.getText().trim().equals("")) {
            Utils.Alert("Answer 2 should not be empty");
            answer2.requestFocus();
            return null;
        }
        Answers[1] = answer2.getText().trim();

        // Answer 3
        if (answer3.getText().trim().equals("")) {
            Utils.Alert("Answer 3 should not be empty");
            answer3.requestFocus();
            return null;
        }
        Answers[2] = answer3.getText().trim();

        // Answer 4
        if (answer4.getText().trim().equals("")) {
            Utils.Alert("Answer 4 should not be empty");
            answer4.requestFocus();
            return null;
        }
        Answers[3] = answer4.getText().trim();

        // Correct answer
        int correctAnswer = 0;
        if (jRadioButton2.isSelected()) {
            correctAnswer = 1;
        }
        else if (jRadioButton3.isSelected()) {
            correctAnswer = 2;
        }
        else if (jRadioButton4.isSelected()) {
            correctAnswer = 3;
        }

        data = new QuestionModel(catID, Question, Answers, correctAnswer);
        return data;
    }
    
    private QuestionModel questionData;

    public AdminNewQA loadData(QuestionModel q) {
        this.questionData = q;
        return loadData(q.getQuestionID(), q.getQuestion(), q.getAnswers(), q.getCorrectAnswer(), q.getCatID(), q.getAnswersID());
    }

    public AdminNewQA loadData(int QID, String question, String[] Answers, int correctChoice, int CatID, int[] anwsersID) {
        this.questionData = new QuestionModel(QID, CatID, question, Answers, anwsersID, correctChoice);

        this.tfQuestion.setText(question);
        category.setSelectedItem(categoryMap.get(CatID));
        answer1.setText(Answers[0]);
        answer2.setText(Answers[1]);
        answer3.setText(Answers[2]);
        answer4.setText(Answers[3]);

        switch (correctChoice) {
            case 0:
                jRadioButton1.setSelected(true);
                break;
            case 1:
                jRadioButton2.setSelected(true);
                break;
            case 2:
                jRadioButton3.setSelected(true);
                break;
            case 3:
                jRadioButton4.setSelected(true);
                break;
        }
        this.setTitle("Edit Question ID: " + QID);
        return this;
    }

    public AdminNewQA resetData() {
        QuestionID = 0;
        answer1.setText("");
        answer2.setText("");
        answer3.setText("");
        answer4.setText("");
        jRadioButton1.setSelected(true);
        tfQuestion.setText("");
        if (category.getItemCount() > 0) {
            category.setSelectedIndex(0);
        }
        return this;
    }

    public AdminNewQA resetAllData() {
        this.LoadCategoryData();
        return resetData();
    }
    private boolean QAEditMode = false;

    public AdminNewQA setQAEditMode(boolean Edit) {
        this.QAEditMode = Edit;
        if (Edit && QuestionID > 0) {
            setTitle("Edit Question ID: " + QuestionID);
        }
        else if (!Edit) {
            this.resetData();
            setTitle("Add new Question");
        }
        return this;
    }
    
    

    

/**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(AdminNewQA.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AdminNewQA.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AdminNewQA.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AdminNewQA.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new AdminNewQA().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField answer1;
    private javax.swing.JTextField answer2;
    private javax.swing.JTextField answer3;
    private javax.swing.JTextField answer4;
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnReset;
    private javax.swing.JButton btnSave;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.ButtonGroup buttonGroup2;
    private javax.swing.JComboBox category;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JRadioButton jRadioButton1;
    private javax.swing.JRadioButton jRadioButton2;
    private javax.swing.JRadioButton jRadioButton3;
    private javax.swing.JRadioButton jRadioButton4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea tfQuestion;
    // End of variables declaration//GEN-END:variables
}
